package com.quanxiaoha.xiaohashu.oss.biz.factory;

import com.quanxiaoha.xiaohashu.oss.biz.strategy.FileStrategy;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@RefreshScope
public class FileStrategyFactory implements InitializingBean, ApplicationContextAware {

    @Value("${storage.type}")
    private String strategyType;

    private ApplicationContext applicationContext;

    private static final Map<String, FileStrategy> STRATEGY_MAP = new HashMap<>();

    public FileStrategy chooseStrategy(String type) {
        FileStrategy strategy = STRATEGY_MAP.get(type);
        if (strategy == null) {
            throw new IllegalArgumentException("不可用的存储类型: " + type);
        }
        return strategy;
    }

    public FileStrategy getFileStrategy() {
        return chooseStrategy(strategyType);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, FileStrategy> beansOfType = applicationContext.getBeansOfType(FileStrategy.class);
        // v.mark()为策略对应的key，value为策略对象
        beansOfType.forEach((k, v) -> STRATEGY_MAP.put(v.mark(), v));
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
